
#pragma once
#pragma comment(lib,"lua5_1.lib")
#pragma warning(disable: 4996)

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include <typeinfo>

class LuaOperate
{
private:
	static lua_State *L_luaState;
	static LuaOperate* I_operate;

	LuaOperate();

public:
	static LuaOperate* GetInstance(char* filename = NULL);

	template<typename T>bool GetValueByName(char *pName,T *pOut);
	bool GetValueByName(char *pName,char* pOut);


	//////////////////////////////////////////////////////////////////////////

	int getGlobal(lua_State *l,char * varname);
	float getGlobalNumber(lua_State *l ,char * varname);
	float getField (const char *key);
	float getNumber (const lua_Number num) ;

	void GetTableNum(char * tablename);
	//////////////////////////////////////////////////////////////////////////

	bool ReloadFile(char* filename = NULL);
	~LuaOperate();
};

template<typename T>
bool LuaOperate::GetValueByName(char *pName,T *pOut)
{
	lua_getglobal(L_luaState,pName);
	if(!lua_isnumber(L_luaState,-1))
	{
		return false;//strcpy(pOut,lua_tostring(L,-1));
	}
	else
	{
		if(strcmp(typeid(*pOut).name(),"int") == 0)
		{
			*pOut = (int)lua_tonumber(L_luaState,-1);
		}
		else if(strcmp(typeid(*pOut).name(),"float") == 0)
		{
			*pOut = (int )(float)lua_tonumber(L_luaState,-1);
		}
		else if(strcmp(typeid(*pOut).name(),"double") == 0)
		{
			*pOut = (int )(double)lua_tonumber(L_luaState,-1);
		}
		/*else if(strcmp(typeid(*pOut).name(),"string") == 0)
		{
			*pOut = (char)lua_tostring(L,-1);
		}*/
		else
		{
			return false;
		}
	}

	return true;
};
